package com.x.client.activity

import android.support.v4.content.ContextCompat
import android.support.v4.view.GravityCompat
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.chad.library.adapter.base.BaseQuickAdapter
import com.gg.baselibrary.BaseActivity
import com.gg.image.config.GlideApp
import com.gg.utils.StatusUtils
import com.gg.utils.isNullOrZero
import com.gg.widget.LoadUtils
import com.gg.widget.WaveSideBar
import com.gg.widget.navigationbar.DefaultNavigationBar
import com.lsxiao.apollo.core.Apollo
import com.socks.library.KLog
import com.x.client.R
import com.x.client.adapter.BrandAdapter
import com.x.client.adapter.SeriesAdapter
import com.x.client.bean.Brand
import com.x.client.bean.BrandItem
import com.x.client.bean.CarStateBus
import com.x.client.bean.Series
import com.x.client.net.ApiFactory
import com.x.client.net.Composers
import com.x.client.utils.BusTag
import com.x.client.utils.RouterClass
import com.x.client.utils.RouterField
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_brand.*
import kotlinx.android.synthetic.main.activity_brand_series.*

/**
 * Creator : GG
 * Date    : 2018/5/22
 * Mail    : gg.jin.yu@gmai.com
 * Explain :
 */
@Route(path = RouterClass.brand)
class BrandActivity : BaseActivity(), WaveSideBar.OnSelectIndexItemListener {


    override fun getLayoutRes(): Int = R.layout.activity_brand_series


    private val data: ArrayList<BrandItem> = arrayListOf()

    private val mBrandAdapter = BrandAdapter(data = data)
    private val seriesAdapter = SeriesAdapter()

    private val brandManager by lazy { LinearLayoutManager(this) }
    private val seriesManager by lazy { LinearLayoutManager(this) }

    private var mPosition: Int = 0

    private lateinit var title: TextView

    @Autowired(name = RouterField.type)
    @JvmField
    var mType: String? = ""

    @Autowired(name = RouterField.data)
    lateinit var bus: CarStateBus

    override fun initArguments() {
        super.initArguments()
        if (!this::bus.isInitialized)
            bus = CarStateBus()
    }

    override fun initTitle() {
        super.initTitle()
        KLog.w("tag", "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")
        StatusUtils.setStatusTextColor(true, this)
        StatusUtils.setStatusBar(this, false, false)
        DefaultNavigationBar.Builder(this)
                .setLeftIcon(R.drawable.ic_back_black)
                .setMiddleTextColor(ContextCompat.getColor(this, R.color.text_black))
                .setBackgroundColor(ContextCompat.getColor(this, R.color.white))
                .setStatusBarHeight(StatusUtils.getStatusBarHeight(this))
                .setBackgroundColor(ContextCompat.getColor(this, R.color.white))
                .setLeftClickListener(View.OnClickListener { finish() })
                .setMiddleClickListener(View.OnClickListener { drawerLayout.openDrawer(GravityCompat.START) })
                .setMiddleText("品牌车系")
                .create()


    }

    override fun initView() {

        letterSideBar.setOnSelectIndexItemListener(this)

        title = findViewById(R.id.title_text)!!
        recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL).apply {
            setDrawable(ContextCompat.getDrawable(this@BrandActivity, R.drawable.divider_ll_grey_h)!!)
        })

        seriesRecyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL).apply {
            setDrawable(ContextCompat.getDrawable(this@BrandActivity, R.drawable.divider_ll_grey_h)!!)
        })

        header.visibility = View.VISIBLE

        recyclerView.layoutManager = brandManager

        seriesRecyclerView.layoutManager = seriesManager

        recyclerView.adapter = mBrandAdapter

        seriesRecyclerView.adapter = seriesAdapter


        var height = 0
        var mCurrentPosition = 0
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                height = header.height
            }

            override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (mBrandAdapter.getItemViewType(mCurrentPosition + 1) == BrandItem.TITLE) {
                    val view = brandManager.findViewByPosition(mCurrentPosition + 1)
                    if (view != null) {
                        if (view.top <= height) {
                            header.y = (view.top - height).toFloat()
                        } else {
                            header.y = 0f
                        }
                    }
                }

                if (mCurrentPosition != brandManager.findFirstVisibleItemPosition()) {
                    mCurrentPosition = brandManager.findFirstVisibleItemPosition()

                    if (dy > 0 && mBrandAdapter.getItemViewType(mCurrentPosition + 1) != BrandItem.TITLE) {
                        header.y = 0f
                    } else if (dy < 0 && mBrandAdapter.getItemViewType(mCurrentPosition + 1) == BrandItem.TITLE) {

                        header.y = (-height).toFloat()
                    }
                    updateHeader(data, title, mCurrentPosition)
                }
            }
        })
        updateHeader(data, title, mCurrentPosition)

        mBrandAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            if (mBrandAdapter.data[position].itemType == BrandItem.TITLE)
                return@OnItemClickListener

            if (mBrandAdapter.data[position].brand?.brandId.isNullOrZero()) {
                Apollo.emit(BusTag.carState, bus.apply {
                    brandId = null
                    seriesId = null
                })
                finish()
            }


            mBrandAdapter.data[mPosition].choose = false
            mBrandAdapter.notifyItemChanged(mPosition)
            mBrandAdapter.data[position].choose = true
            mBrandAdapter.notifyItemChanged(position)
            mPosition = position
            setSeriesHeader(mBrandAdapter.data[mPosition])
            drawerLayout.openDrawer(seriesLL)
            bus.brandId = mBrandAdapter.data[position].brand?.brandId
            LoadUtils.show(this)
            getSeries()
        }


        seriesAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->

            bus.seriesId = seriesAdapter.data[position].seriesId
            Apollo.emit(BusTag.carState, bus)
            finish()
        }
        getSeries()
    }

    private fun getSeries() {
        if (bus.brandId.isNullOrZero())
            return
        ApiFactory.getErpApi()
                .series(brandId = bus.brandId!!)
                .compose(Composers.handleError())
                .compose(this.bindToLifecycle())
                .subscribe({
                    it.add(0, Series(seriesName = "不限车系", seriesId = null, logo = R.drawable.ic_no_series))
                    seriesAdapter.setNewData(it)
                    LoadUtils.hidden()
                }, {
                    LoadUtils.hidden()
                })
    }

    override fun initData() {
        LoadUtils.show(this)
        ApiFactory.getErpApi()
                .brand()
                .compose(Composers.handleError())
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.computation())
                .map {
                    it.forEach {
                        val item = BrandItem(BrandItem.TITLE, it.initial, null)
                        data.add(item)
                        it.brandInfo?.forEach {
                            val brandItem = BrandItem(BrandItem.ITEM, it.brandInitial, it)
                            data.add(brandItem)
                        }
                    }
                    return@map data
                }
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.bindToLifecycle())
                .subscribe({
                    it.add(0, BrandItem(itemType = BrandItem.TITLE, title = "不限品牌", item = null))
                    val brandItem = BrandItem(itemType = BrandItem.ITEM, title = "不限品牌", item = Brand(brandName = "不限品牌", noBrandLogo = R.drawable.ic_no_brand, brandId = null))
                    it.add(1, brandItem)
                    setSeriesHeader(brandItem)
                    it.forEach {
                        if (it.brand?.brandId == bus.brandId) {
                            it.choose = true
                            setSeriesHeader(it)
                        }
                    }

                    mBrandAdapter.setNewData(it)
                    LoadUtils.hidden()
                }, {})
    }

    private fun setSeriesHeader(brandItem: BrandItem) {
        if (!brandItem.brand?.noBrandLogo.isNullOrZero()) {
            GlideApp.with(this).load(brandItem.brand?.noBrandLogo).into(logo)
        } else {
            GlideApp.with(this).load(brandItem.brand?.brandLogo).into(logo)
        }

        name.text = brandItem.brand?.brandName
    }


    private fun updateHeader(data: ArrayList<BrandItem>, title: TextView?, mCurrentPosition: Int) {
        if (data.size == 0 || mCurrentPosition < 0 || data.size <= mCurrentPosition) {
            header.visibility = View.GONE
        } else {
            header.visibility = View.VISIBLE
            title?.text = data[mCurrentPosition].title
        }
    }

    override fun onSelectIndexItem(letter: String?) {

        data.forEachIndexed { index, brandItem ->
            if (brandItem.itemType == BrandItem.TITLE) {
                if (brandItem.title == letter) {
                    brandManager.scrollToPositionWithOffset(index, 0)
                }
            }
        }
    }


}